package com.acdc.jobs;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.acdc.service.IIotModuleService;
import com.acdc.device.service.IMeterDeviceService;
import com.acdc.service.DLT698InstructionSender;
import com.acdc.device.domain.MeterDevice;
import java.util.List;
import com.acdc.domain.IotModule;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Component("queryPowerJob")
public class QueryPowerJob {

    @Autowired
    private IIotModuleService iotModuleService;

    @Autowired
    private IMeterDeviceService meterDeviceService;

    @Autowired
    private DLT698InstructionSender dlt698InstructionSender;

    public void execute() {
        MeterDevice query = new MeterDevice();
        query.setDeviceStatus("1");
        List<MeterDevice> meterDeviceList = meterDeviceService.selectMeterDeviceList(query);
        // 根据meterDeviceList大小创建线程池，最多10个线程，每个线程至少处理50个电表
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < meterDeviceList.size(); i += 50) {
            List<MeterDevice> subList = meterDeviceList.subList(i, Math.min(i + 50, meterDeviceList.size()));
            executorService.submit(() -> {
                for (MeterDevice meterDevice : subList) {
                    IotModule iotModule = iotModuleService.selectIotModuleById(meterDevice.getIotModuleId());
                    dlt698InstructionSender.queryForwardPower(iotModule.getImei(), meterDevice.getLogicAddr(), "1");
                }
            });
        }
        executorService.shutdown();
        try {
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
